<?php

class PaypalController extends Controller {

    /**
     * confirm payment success
     * @throws CHttpException
     */
    public function actionConfirm() {
	$token = trim($_GET['token']);
	$payerId = trim($_GET['PayerID']);

	//update model
	$model = Invoice::model()->find('payment_code = :payment_code', array(':payment_code' => $token));

	if (!$model) {
	    //error!!
	    throw new CHttpException(404, 'Page was not exists');
	}

	$result = Yii::app()->Paypal->GetExpressCheckoutDetails($token);

	$result['PAYERID'] = $payerId;
	$result['TOKEN'] = $token;
	$result['ORDERTOTAL'] = $model->total;

	//Detect errors
	if (!Yii::app()->Paypal->isCallSucceeded($result)) {
	    if (Yii::app()->Paypal->apiLive === true) {
		//Live mode basic error message
		$error = 'We were unable to process your request. Please try again later';
	    } else {
		//Sandbox output the actual error message to dive in.
		$error = $result['L_LONGMESSAGE0'];
	    }
	    echo $error;
	    Yii::app()->end();
	} else {
	    $paymentResult = Yii::app()->Paypal->DoExpressCheckoutPayment($result);
	    //Detect errors
	    if (!Yii::app()->Paypal->isCallSucceeded($paymentResult)) {
		if (Yii::app()->Paypal->apiLive === true) {
		    //Live mode basic error message
		    $error = 'We were unable to process your request. Please try again later';
		} else {
		    //Sandbox output the actual error message to dive in.
		    $error = $paymentResult['L_LONGMESSAGE0'];
		}
		echo $error;
		Yii::app()->end();
	    } else {
		//payment was completed successfully
		//update payment status
		$model->status = Invoice::STATUS_APPROVE;

		if ($model->model == Invoice::MODEL_AD) {
		    //update ad expired
		    $ad = Ad::model()->findByPk($model->model_id);

		    if ($ad) {
			//get duration
			$params = CJSON::decode($model->params);

			//if ads is expired or created new
			if ($ad->expire_time < time()) {

			    //3 months. for resume
			    if ($ad instanceof Resume) {
				$ad->expire_time = strtotime('+3 months');
			    } else {
				if ($ad instanceof CompanySource) {
				    //check whether user post eblast
				    $eblast = Eblast::model()->find('ad_id = ' . $ad->ad_id);
				    if ($eblast) {
					$eblast->status = Eblast::STATUS_PAID;
					$eblast->save();
				    }
				    if ($ad->featured == Ad::IS_FEATURED) {
					$ad->expire_featured = strtotime('+1 month');
				    }
				}
				switch ($params['duration']) {

				    case "price_6_month":
					$ad->expire_time = strtotime('+6 months');
					break;
				    case "price_one_year":
					$ad->expire_time = strtotime('+1 year');
					break;
				    case "price_3_month": default:
					$ad->expire_time = strtotime('+3 months');
					break;
				    case "price_two_week":
					$ad->expire_time = strtotime('+2 weeks');
					break;
				    case "price_one_month": default:
					$ad->expire_time = strtotime('+1 month');
					break;
				}
//			if (isset($params['duration'])) {
//			    $duration = $params['duration'];
//			} else {
//			    $duration = 2;
//			}
//
//			switch ($duration) {
//			    case 1:
//				$ad->expire_time = time() + strtotime('+1 month');
//				break;
//			    case 2 : default :
//				$ad->expire_time = time() + strtotime('+2 weeks');
//				break;
//			}
			    }
			} else {
			    //if user's ads is not expired, for renew
			    //get Odd time
			    $oddTime = $ad->expire_time - time();
			    switch ($params['duration']) {
				case "price_6_month":
				    $ad->expire_time = strtotime('+6 months') + $oddTime;
				    break;
				case "price_one_year":
				    $ad->expire_time = strtotime('+1 year') + $oddTime;
				    break;
				case "price_3_month": default:
				    $ad->expire_time = strtotime('+3 months') + $oddTime;
				    break;
				case "price_two_week":
				    $ad->expire_time = strtotime('+2 weeks') + $oddTime;
				    break;
				case "price_one_month": default:
				    $ad->expire_time = strtotime('+1 month') + $oddTime;
				    break;
			    }
			}
			$ad->is_send_mail = Ad::NOT_SEND_MAIL;
			$ad->is_send_mail_before = Ad::NOT_SEND_MAIL;
			$ad->status = Ad::STATUS_APPROVE;
			$ad->isNewRecord = FALSE;
			$ad->save();
		    }
		} else {

		    /*
		     * set status is approved for event when payment is completed
		     */
		    if ($model->model == Invoice::MODEL_EVENT) {
			$event = Event::model()->findByPk($model->model_id);
			$event->status = Event::STATUS_APPROVE;
			$event->save();
		    }
		}

		if ($model->save()) {
		    $this->render('confirm');
		}
	    }
	}
    }

    public function actionCancel() {
	//The token of the cancelled payment typically used to cancel the payment within your application
	$token = $_GET['token'];

	$this->render('cancel');
    }

}

